
package com.bear.cmcc.NetTestHTTP.service;

import com.bear.cmcc.NetTestHTTP.NetworkTestApp;
import com.bear.cmcc.NetTestHTTP.component.PowerLock;
import com.bear.cmcc.NetTestHTTP.constant.FtpConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.db.DBCellsHelper;
import com.bear.cmcc.NetTestHTTP.util.FtpUtil;
import com.bear.cmcc.NetTestHTTP.util.SetUtil;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * 下载小区数据，并插入至数据库中
 * 此耗时较长，下载小区，耗时：176秒
 * 小区数据6万多条，耗时：
 * @author suchangjun
 */
public class LocalUpdateVillageDBService extends Service {
	
	private static final String TAG = "LocalUpdateVillageDBService";
	
	public static final String ISBACKRUN = "isbackrun";//是否后台运行

    private PowerLock powerLock;
    
    private Context context;
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onCreate() {
        super.onCreate();
        try {
            powerLock = new PowerLock(this, "NetSpeedInfoService");
            this.context = this;
            startDownFile();
        } catch (Exception e) {
            if (e != null) {
                e.printStackTrace();
            }
        }
    }    

    @Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		if(intent!=null){
			if(NetworkTestApp.isStop_celldb){
				stopSelf();
			}
		}
	}

	/**
     * 启动一个下载文件进程。
     * 
     * @param context
     */
    private void startDownFile() {

        powerLock.acquireWakeLock();
        Thread thread = new Thread() {

            @Override
            public void run() {
            	try {
                    //下载服务端的csv小区数据
                    sendFileDownBroad(MyCommonConstant.PrivateActionName.SERVICE_DOWN_VILLAGE_TYPE_CSV, 0, 0);
                    Log.d(TAG, "downing-csv");
                    String dbFileName = FtpConstant.FtpFileNames.dbFileName;
                    if(!FtpUtil.downloadFileByComFTP(context, dbFileName, dbFileName, false, LocalUpdateVillageDBService.this)){
                    	//下载 csv文件失败
                    	sendFileDownBroad(MyCommonConstant.PrivateActionName.SERVICE_DOWN_VILLAGE_TYPE_CSV, -1, 0);
                    	if(powerLock!=null){
                    		powerLock.releaseWakeLock();
                        }
                        stopSelf();//把自己这个服务停止
                    }else{
                    	//csv下载成功，进入小区导入数据库：
                    	DBCellsHelper db = new DBCellsHelper(context);
                    	db.insertVillageDB(LocalUpdateVillageDBService.this);
                    	db.close();
                    	if(powerLock!=null){
                    		powerLock.releaseWakeLock();
                        }
                        stopSelf();// 数据下载完成，把自己这个服务停止
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();

    }

    /**
     * 小区信息导入数据库的广播发送
     * @param downType 操作类型：（下载csv,插入DB）
     * @param status 发送消息的状态(-1:导入信息出错,0:正在下载（导入）,1:导入完成)
     * @param currentPro 当前的进度 
     */
    public void sendFileDownBroad(String downType,int status,int currentPro) {
        sendFileDownBroad(downType, status, currentPro, "");
    }
    
    /**
     * 小区信息导入数据库的广播发送
     * @param downType 操作类型：（下载csv,插入DB）
     * @param status 发送消息的状态(-1:导入信息出错,0:正在下载（导入）,1:导入完成)
     * @param currentPro 当前的进度 
     * @param cellName 当前导入的小区名称
     */
    public void sendFileDownBroad(String downType,int status,int currentPro,String cellName) {
        try {
        	if(NetworkTestApp.isStop_celldb){
        		//取消更新
        		stopSelf();
        		return ;
        	}
        	
        	Log.d(TAG, "sendFileDownBroad-downType:"+downType+",status:"+status+",currentPro:"+currentPro+",cellName:"+cellName);
            Intent intent = new Intent(MyCommonConstant.PrivateActionName.NET_WORK_VILLAGE_DATA_DOWN);
            intent.putExtra(MyCommonConstant.PrivateActionName.SERVICE_DOWN_VILLAGE_TYPE, downType);
            intent.putExtra(MyCommonConstant.PrivateActionName.SERVICE_DOWN_VILLAGE_STATUS, status);
            intent.putExtra(MyCommonConstant.PrivateActionName.SERVICE_DOWN_VILLAGE_CURRENTPRO, currentPro);
            intent.putExtra(MyCommonConstant.PrivateActionName.SERVICE_DOWN_VILLAGE_CURRENTNAME, cellName);
            sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void onDestroy() {
        try {
            powerLock.releaseWakeLock();
            powerLock = null;
        } catch (Exception e) {
            if (e != null) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }
    
    
}
